package ${location}.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.Date;

/**
 * @author ${author}
 */
@Configuration
public class MetaObjectConfig implements MetaObjectHandler {
	private static final String CREATE = "create";
	private static final String UPDATE = "update";

	@Override
	public void insertFill(MetaObject meta) {
		fieldMatching(meta, CREATE, UPDATE);
	}

	@Override
	public void updateFill(MetaObject meta) {
		fieldMatching(meta, UPDATE);
	}

	private void fieldMatching(@NotNull MetaObject meta, String... strings) {
		for (String name : meta.getGetterNames()) {
			Class<?> type = meta.getSetterType(name);
			for (String string : strings) {
				if (name.contains(string)) {
					timeTypeDeal(meta, name, type);
				}
			}
		}
	}

	private void timeTypeDeal(MetaObject meta, String name, @NotNull Class<?> type) {
		String typeName = type.getName();
		if (typeName.equals(Date.class.getName())) {
			meta.setValue(name, new Date());
		} else if (typeName.equals(LocalDate.class.getName())) {
			meta.setValue(name, LocalDate.now(ZoneId.systemDefault()));
		} else if (typeName.equals(LocalDateTime.class.getName())) {
			meta.setValue(name, LocalDateTime.now(ZoneId.systemDefault()));
		} else if (typeName.equals(LocalTime.class.getName())) {
			meta.setValue(name, LocalTime.now(ZoneId.systemDefault()));
		}
	}
}
